// 1. 定义本地化代理
import 'dart:convert';

import 'package:eshi/app/SettingsPage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class AppLocalizations {
  AppLocalizations(this.locale);

  final Locale locale;

  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations)!;
  }

  static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();

  Map<String, String> _localizedStrings = {};

  Future<void> load() async {
    _instance = this;
    // 加载对应语言的翻译文件
    String jsonString = await rootBundle.loadString('lib/app/settings/languages/$locale.json');
    Map<String, dynamic> jsonMap = json.decode(jsonString);
    _localizedStrings = jsonMap.map((key, value) {
      return MapEntry(key, value.toString());
    });
    _localizedStrings.length;
  }

  Set trkeys = {};
  // 翻译方法
  static const isDebug = false;
  String translate(String key) {
    if(isDebug && !trkeys.contains(key) && _localizedStrings[key]==null){
      print(key);
      trkeys.add(key);
    }
    return _localizedStrings[key] ?? key;
  }
  static  AppLocalizations? _instance;
  
  static  t(String key){
    return (_instance!=null) ? _instance!.translate(key) :key;
  }
}

class _AppLocalizationsDelegate
    extends LocalizationsDelegate<AppLocalizations> {
  const _AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    var code = locale.toString();
    // 支持的语言
    return Language.values.any((p) => p.code == code );
  }

  @override
  Future<AppLocalizations> load(Locale locale) async {
    AppLocalizations localizations = AppLocalizations(locale);
    await localizations.load();
    return localizations;
  }

  @override
  bool shouldReload(_AppLocalizationsDelegate old) => false;
}